﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace SmallSpider.Class
{
    public class HttpAnalysis
    {
        HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
        public HttpAnalysis(string strSrc)
        {
            doc.LoadHtml(strSrc);
        }

        /// <summary>取Html源码中所有链接</summary>
        /// <param name="strSrc"></param>
        /// <returns></returns>
        public List<Link> GetAllLink(string strSrc)
        {
            List<Link> array = new List<Link>();
            MatchCollection matches =
                    Regex.Matches(strSrc, "<a\\s+([^>h]|h(?!ref\\s))*(?<=[\\s+]?href[\\s+]?=[\\s+]?('|\")?)([^\"|'>]+?(?=\"|'))(.+?)?((?<=>)(.+?)?(?=</a>))", RegexOptions.IgnoreCase);

            foreach (Match _Match in matches)
            {
                Link _Link = new Link();
                _Link.Url = _Match.Groups[3].Value;
                _Link.Text = _Match.Groups[5].Value;
                array.Add(_Link);
            }
            return array;
        }
        /// <summary>页面Title</summary>
        /// <returns></returns>
        public string GetHtmlTitle()
        {
            if (doc.DocumentNode.SelectNodes("//html//head//title") != null)
            {
                return doc.DocumentNode.SelectNodes("//html//head//title")[0].InnerHtml;
            }
            return string.Empty;
        }

        public string GetHtmlKeywords()
        {
            if (doc.DocumentNode.SelectNodes("//html//head//meta[@name='keywords']") != null)
            {
                if (doc.DocumentNode.SelectNodes("//html//head//meta[@name='keywords']")[0].Attributes["content"] != null)
                {
                    return doc.DocumentNode.SelectNodes("//html//head//meta[@name='keywords']")[0].Attributes["content"].Value;
                }
            }
            return string.Empty;
        }

        public string GetHtmlDescription()
        {
            if (doc.DocumentNode.SelectNodes("//html//head//meta[@name='description']") != null)
            {
                if (doc.DocumentNode.SelectNodes("//html//head//meta[@name='description']")[0].Attributes["content"] != null)
                {
                    return doc.DocumentNode.SelectNodes("//html//head//meta[@name='description']")[0].Attributes["content"].Value;
                }
            }
            return string.Empty;
        }

    }
}
